package hoowin.common.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;

import hoowin.basic.util.Encoder;
import hoowin.common.dao.IFileItemDao;
import hoowin.common.model.FileItem;

public class FileService {
	private IFileItemDao fileItemDao;
	private final String storageDir = "/home/storage/";
	//private final String storageDir = "D://temp/";

	public String prepareDownload(FileItem fi){
		FileItem fileItem = fileItemDao.getFileItemById(fi.getId());
		if(fileItem==null)return "error.1100";
		else
			try {
				if(Encoder.encryptMD5(fi.getKey()).equals(fileItem.getKey())){
					fi.setItemContentType(fileItem.getItemContentType());
					fi.setItemFileName(fileItem.getItemFileName());
					fi.setSize(fileItem.getSize());
					fi.setItem(new File(storageDir+fileItem.getId()));
					return "success";
				}else{
					return "error.1101";
				}
			} catch (NoSuchAlgorithmException e) {
				return "exception.1000";
			}
	}
	
	public int saveFile(FileItem fi){
		if(fi.getSize()>0&&fi.getItemFileName()!=null&&fi.getItemFileName().length()!=0){
			try {
				fi.setKey(Encoder.encryptMD5(fi.getKey()));
			} catch (NoSuchAlgorithmException e1) {
				return 0;
			}
			int fileId = fileItemDao.saveFileItem(fi);
			try {
				InputStream in = new FileInputStream(fi.getItem());
				OutputStream out = new FileOutputStream(new File(storageDir+fileId));
				byte[] buffer = new byte[10240];
				int len;
				len = in.read(buffer);
				while(len>0){
					out.write(buffer,0,len);
					len = in.read(buffer);
				}
				in.close();
				out.flush();
				out.close();
				return fileId;
			} catch (FileNotFoundException e) {
				return 0;
			}catch (IOException e) {
				return 0;
			}
			
		}else return 0;
	}
	
	public void setFileItemDao(IFileItemDao fileItemDao) {
		this.fileItemDao = fileItemDao;
	}

	public IFileItemDao getFileItemDao() {
		return fileItemDao;
	}
	
}
